const fs = require('fs');
const path = require('path');
const {parse} = require('node-html-parser')
const {glob} = require('glob');
const urlRegex =require('url-regex');
//获取外部链接的正则表达式
const rulPattern = /(https?:\/\/[^/]*)/i;
const urls = new Set();
//遍历dist目录中的所有HTML，js，css文件
async function searchDomain(){
    const files = await glob('dist/**/*.{html,js,css}')
    for(const file of files){
        const source = fs.readFileSync(file, 'utf-8');
        const matches = source.match(urlRegex({strict: true}))
        if(matches){
            matches.forEach((url)=>{
                const match = url.match(rulPattern)
                if(match && match[1]){
                    urls.add(match[1])
                }
            })
        }
    }
    
}
async function insertLinks(){
    const files = await glob('dist/**/*.html');
    const links =[...urls]
    .map((url)=> `<link rel="dns-prefetch" href="${url}">`)
    .join('\n');
    for(const file of files){
        const html = fs.readFileSync(file, 'utf-8');
        const root = parse(html);
        const head = root.querySelector('head');
        head.insertAdjacentHTML('afterbegin', links);
        fs.writeFileSync(file, root.toString());
    }
}
async function main(){
    await searchDomain();
    //在<head>标签中插入dns-prefetch链接
    await insertLinks();
    [...urls].forEach((url)=>{
        console.log(`预解析 ${url}` );
    })
    console.log('预解析link 标签添加完毕')
}
main()
